<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of OauthController
 *
 * @author dung
 */
class OauthController extends BaseController
{

    //put your code here
    public function getLoginWithFacebook()
    {
        // get data from input
        $code = Input::get('code');

        // get fb service
        $fb = OAuth::consumer('Facebook');

        // check if code is valid
        // if code is provided get user data and sign in
        if (!empty($code)) {

            // This was a callback request from facebook, get the token
            $token = $fb->requestAccessToken($code);

            // Send a request with it
            $ouser = json_decode($fb->request('/me'), true);
//            $fb->request('/me/feed','POST',array('message'=>'aaaaaaaaaaaa'));
            // find exists email
            $user = User::where('email', $ouser['email'])->first();

            if (is_null($user)) {
                try {
                    $birthday = array(0, 0, 0);
                    if (isset($ouser['birthday'])) {
                        $birthday = explode('/', $ouser['birthday']);
                    }
                    $user = Sentry::register(array(
                        'username' => $ouser['email'],
                        'password' => $ouser['email'] . '1234',
                        'first_name' => $ouser['first_name'],
                        'middle_name' => $ouser['middle_name'],
                        'last_name' => $ouser['last_name'],
                        'email' => $ouser['email'],
                        'birth_day' => $birthday[1],
                        'birth_month' => $birthday[0],
                        'birth_year' => $birthday[2],
                        'website' => isset($ouser['website']) ? $ouser['website'] : $ouser['link'],
                        'fb_user' => isset($ouser['username']) ? $ouser['username'] : $ouser['id'],
                        'fb_id' => $ouser['id'],
                        'fb_link' => $ouser['link'],
                        'activated' => 1,
                    ));
                    $memberGroup = Sentry::findGroupById(Config::get('constants.MEMBER_GROUP'));
                    $user->addGroup($memberGroup);
                } catch (Cartalyst\Sentry\Users\UserExistsException $e) {
                    $this->messageBag->add('email', Lang::get('auth/message.account_already_exists'));
                }
            } else {

            }
            if ($user) {
                try {
                    // Try to log the user in
                    Sentry::loginAndRemember($user);

                    // Get the page we were before
                    $redirect = Session::get('loginRedirect', 'account');

                    // Unset the page we were before from the session
                    Session::forget('loginRedirect');

                    // Redirect to the users page
                    return Redirect::to('/')->with('success', Lang::get('auth/message.signin.success'));
                } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
                    $this->messageBag->add('email', Lang::get('auth/message.account_not_found'));
                } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) {
                    $this->messageBag->add('email', Lang::get('auth/message.account_not_activated'));
                } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) {
                    $this->messageBag->add('email', Lang::get('auth/message.account_suspended'));
                } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) {
                    $this->messageBag->add('email', Lang::get('auth/message.account_banned'));
                }
            }
        } // if not ask for permission first
        else {
            // get fb authorization
            $url = $fb->getAuthorizationUri();

            // return to facebook login url
            return Redirect::to((string)$url);
        }
    }

    public function loginWithGoogle()
    {

        // get data from input
        $code = Input::get('code');

        // get google service
        $googleService = OAuth::consumer('Google');

        // check if code is valid
        // if code is provided get user data and sign in
        if (!empty($code)) {

            // This was a callback request from google, get the token
            $token = $googleService->requestAccessToken($code);

            // Send a request with it
            $result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);

            $message = 'Your unique Google user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
            echo $message . "<br/>";

            //Var_dump
            //display whole array().
            dd($result);
        } // if not ask for permission first
        else {
            // get googleService authorization
            $url = $googleService->getAuthorizationUri();

            // return to google login url
            return Redirect::to((string)$url);
        }
    }

    public function loginWithTwitter()
    {

        // get data from input
        $token = Input::get('oauth_token');
        $verify = Input::get('oauth_verifier');

        // get twitter service
        $tw = OAuth::consumer('Twitter');

        // check if code is valid
        // if code is provided get user data and sign in
        if (!empty($token) && !empty($verify)) {

            // This was a callback request from twitter, get the token
            $token = $tw->requestAccessToken($token, $verify);

            // Send a request with it
            $result = json_decode($tw->request('account/verify_credentials.json'), true);

            $message = 'Your unique Twitter user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
            echo $message . "<br/>";

            //Var_dump
            //display whole array().
            dd($result);
        } // if not ask for permission first
        else {
            // get request token
            $reqToken = $tw->requestRequestToken();

            // get Authorization Uri sending the request token
            $url = $tw->getAuthorizationUri(array('oauth_token' => $reqToken->getRequestToken()));

            // return to twitter login url
            return Redirect::to((string)$url);
        }
    }

    public function loginWithLinkedin()
    {

        // get data from input
        $code = Input::get('code');

        $linkedinService = OAuth::consumer('Linkedin');


        if (!empty($code)) {

            // This was a callback request from linkedin, get the token
            $token = $linkedinService->requestAccessToken($code);
            // Send a request with it. Please note that XML is the default format.
            $result = json_decode($linkedinService->request('/people/~?format=json'), true);

            // Show some of the resultant data
            echo 'Your linkedin first name is ' . $result['firstName'] . ' and your last name is ' . $result['lastName'];


            //Var_dump
            //display whole array().
            dd($result);
        } // if not ask for permission first
        else {
            // get linkedinService authorization
            $url = $linkedinService->getAuthorizationUri(array('state' => 'DCEEFWF45453sdffef424'));

            // return to linkedin login url
            return Redirect::to((string)$url);
        }
    }

}
